// Copyright (c) Huawei Technologies Co., Ltd. 2025. All rights reserved.
// This source file is part of the Cangjie project, licensed under Apache-2.0
// with Runtime Library Exception.
//
// See https://cangjie-lang.cn/pages/LICENSE for license information.

#if defined(PLATFORM_WINDOWS)
#include <windows.h>
#elif defined(PLATFORM_LINUX) || defined(PLATFORM_MACOS)
#include <unistd.h>
#include <climits>
#endif
#if defined(PLATFORM_MACOS)
#include <libproc.h>
#endif

#include "Platform/System.h"

namespace Platform::System {

#if defined(PLATFORM_WINDOWS)
const std::string NewLine = "\r\n";
#elif defined(PLATFORM_LINUX) || defined(PLATFORM_MACOS)
const std::string NewLine = "\n";
#endif

#if defined(PLATFORM_WINDOWS)
const std::string CmdChainIfSuccess = " & ";
const std::string CmdChainIfFail = " || ";
#elif defined(PLATFORM_LINUX) || defined(PLATFORM_MACOS)
const std::string CmdChainIfSuccess = " && ";
const std::string CmdChainIfFail = " || ";
#endif

Path GetExecutablePath()
{
    std::string path;
#if defined(PLATFORM_WINDOWS)
    char buffer[MAX_PATH];
    if (GetModuleFileNameA(nullptr, buffer, MAX_PATH) == 0) {
        throw std::runtime_error("Failed to get executable path");
    }
    path = buffer;
#elif defined(PLATFORM_LINUX)
    char buffer[PATH_MAX];
    if (readlink("/proc/self/exe", buffer, sizeof(buffer)) == -1) {
        throw std::runtime_error("Failed to get executable path");
    }
    path = buffer;
#elif defined(PLATFORM_MACOS)
    char buffer[PATH_MAX];
    int size = proc_pidpath(getpid(), buffer, sizeof(buffer));
    if (size <= 0) {
        throw std::runtime_error("Failed to get executable path on macOS");
    }
    path = buffer;
#endif
    return path;
}

} // namespace Platform::System
